<?

/*************************************************************************************

	MySQLi Database Class
	Version : 2.070901
	Author	: Steven Miles
	Requirments:
		mysqli

*************************************************************************************/



class classMySQLi {
	// Database Connection Details
	var $username 	= '';
	var $password 	= '';
	var $database 	= '';
	var $server 	= 'localhost'; 
	var $port		= '3306';
	
	
	// Database Connection Link
	var $connection = NULL;


	// Temporary Variables
	
	var $insertID  = NULL;
	
	var $lastError = NULL;
	
	
	// Class Contructor Funciton, Store Connection Details;
	public function __construct($params='') {
//		if (isset($crm->profile->Database)){
			foreach($params AS $name=>$value){
				switch ($name) {
					case 'database':
					case 'name':
						$this->database = $value;
						break;
					case 'user':
					case 'username':
						$this->username = $value;
							break;
					case 'password':
					case 'pass':
						$this->password = $value;
						break;
					case 'server':
					case 'host':
						$this->server = $value;
						break;
					case 'port':
						$this->port = $value;
						break;
				}
			}
		//}
	}
	
	
	// Make Connection to MySQL Server	
	private function connect() {	
		if ($this->connection == NULL ) {
			if ($this->connection = new mysqli($this->server,$this->username,$this->password,$this->database)) { 
	  			$this->connection->set_charset("utf8");
	  			if (mysqli_connect_errno()) {
   					 printf("Connect failed: %s\n", mysqli_connect_error());
					 return false;
				} else {
					return true;
					if ($this->setTimeZone()) {
						return true;
					} else {
						echo $this->lastError;
						exit();
						return false;
					}
				}
			} else return false;
		}
	}
	// Disconnection From Database
  	private function disconnect() {
		if ($this->connection != NULL) {
			$this->connection->close();
			$this->connection = NULL;
		}
	}

	public function setTimeZone($zone = 'Australia/Queensland') {
		return $this->query("SET SESSION time_zone='".$zone."';");
	}


	public function query($sql) {
		global $crm;
		$this->connect();
		if ($this->result = $this->connection->query($sql)) {
			if (strtoupper(substr($sql,0,6)) == "INSERT") { $this->insertID = $this->connection->insert_id;}
			return true;
		} else {
			if (isset($crm->logs)) {
				$crm->logs->error(array(
					'description' => 'Database Error',
					'error_msg' => '<b>Database Query Details</b><br/><br/>'.$sql.'<br/><br/><b>Last Database Error </b> '.$this->connection->error,
					'type' => 'security',
					'module' => 'Database',
				));
			}
			$this->lastError = $this->connection->error;
			return false;
		}				
	}

	public function fetchObj() {
		return $this->connection->fetch_object();
	}
	public function getObject($sql){
		return $this->getObjects($sql,false);
	}
	

	public function getObjects($sql,$multiple = true) {
		$this->connect();
		$output = array();
		if ($this->query($sql)) {
			if ($multiple == true) {
				while ($row = $this->result->fetch_object()) {
					$output[] = $row;
				}
			} else $output = $this->result->fetch_object();
			$this->result->free();
		}
		return $output;	
	}


	public function getArrays($sql,$multiple = true) {
		$this->connect();
		$output = array();
		if ($this->query($sql)) {
			if ($multiple == true) {
				while ($row = $this->result->fetch_assoc()) {
					$output[] = $row;
				}
			} else $output = $this->result->fetch_assoc();
			$this->result->free();
		}
		return $output;	
	}
	
	public function escape($string) {
		$this->connect();
		return $this->connection->escape_string($string);	
	}
	
	
	public function resultsCount() {
		$total = $this->getFoundRows();
		if ($total == 0) {
			return 0;
		} else return (int)$total;
	}
	
	
	private function getFoundRows() {
		$sql = "SELECT FOUND_ROWS() AS total;";
		$result = $this->getObjects($sql,false);
		return $result->total;
	}
	
	
	public function version() {
		$db = $this->getObject("SELECT version() AS version;");
		return $db->version;
	}
	public function convertDate($date,$fromFormat){
		$d = 0;
		$m = 0;
		$y = 0;
		$parts = explode('/',$fromFormat);
		$dateParts = explode('/',$date);
		foreach ($parts AS $index=>$part){
			switch (strtolower($part)) {
				case 'd': $d = $dateParts[$index]; break;	
				case 'm': $m = $dateParts[$index]; break;	
				case 'y': $y = $dateParts[$index]; break;	
			}	
		}
		return $y.'-'.$m.'-'.$d;
	}
	
	public function execute($sql,$params) {
		$this->connect();
		$stmt = $this->connection->prepare($sql);
		$types = array();
		$values = array();
		foreach ($params AS $param) {
			if (is_numeric($param) && is_int($param)) {
				$types[] = 'i';
				$values[] = $param;
			} elseif (is_numeric($param) && is_float($param)) {
				$types[] = 'd';
				$values[] = $param;
			} elseif(is_string($param)) {
				$types[] = 's';
				$values[] = $param;
			} elseif (is_binary($param)) {
				$types[] = 'b';
				$values[] = $param;
			}
		}
		$ar = array();
		$ar[] = implode('',$types);
		foreach ($values AS $value) { $ar[] = $value;}
		call_user_func_array(array($stmt, 'bind_param'),$ar);
		$result = $stmt->execute();
		$stmt->close();
		return $result;
	}
}


class objSorting {
	
	public $field = '';
	public $dir = 'ASC';
	public $start = 0;
	public $limit = 100;
	
	public function __construct($data) {
		global $db;
	
		$this->field = isset($data['sort'])?$db->escape($data['sort']):'';
		
		if (isset($data['dir']) && !empty($data['sort'])){
			switch ($data['dir']) {
				case 'ASC' : $this->dir = 'ASC'; break;
				case 'DESC' : $this->dir = 'DESC'; break;		
			}
		}
		
		$this->start = isset($data['start'])?(int)$data['start']:0;
		$this->limit = isset($data['limit'])?(int)$data['limit']:10;
	}

}
?>
